package com.bookhouse.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.bookhouse.dao.BaseDAO;
import com.bookhouse.dao.DAOException;
import com.bookhouse.dao.ReadertypeDAO;
import com.bookhouse.domain.Readertype;
import com.bookhouse.util.HibernateSessionFactory;

public class ReadertypeDAOImpl extends BaseDAO implements ReadertypeDAO {

	@Override
	public void insert(Readertype readertype) throws DAOException {
		Transaction tx = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.save(readertype);
			tx.commit();
		} catch (Exception ex) {
			throw new DAOException("Error adding readertype. " + ex.getMessage());
		} finally {
			if (tx != null)
				tx = null;
			HibernateSessionFactory.closeSession();
		}

	}

	@Override
	public List<Readertype> getReadertype() throws DAOException {
		List<Readertype> list = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			String hql = "from Readertype";
			list = session.createQuery(hql).list();
		} catch (Exception ex) {
			throw new DAOException("Error getting readertype. " + ex.getMessage());
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return list;
	}

	@Override
	public Readertype getReadertype(int id) throws DAOException {
		Readertype readertype = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			readertype = (Readertype) session.get(Readertype.class, id);
		} catch (Exception ex) {
			throw new DAOException("Error getting readertype. " + ex.getMessage());
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return readertype;
	}

	@Override
	public void updateReadertype(Readertype readertype) throws DAOException {
		Transaction tx = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.update(readertype);
			tx.commit();
		} catch (Exception ex) {
			throw new DAOException("Error updating readertype. " + ex.getMessage());
		} finally {
			if (tx != null)
				tx = null;
			HibernateSessionFactory.closeSession();
		}

	}

	@Override
	public void deleReadertype(int id) throws DAOException {
		Transaction tx = null;
		try {
			Session session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Readertype readertype = (Readertype) session.get(Readertype.class, id);
			session.delete(readertype);
			tx.commit();
		} catch (Exception ex) {
			throw new DAOException("Error deleting readertype. " + ex.getMessage());
		} finally {
			if (tx != null)
				tx = null;
			HibernateSessionFactory.closeSession();
		}

	}

}
